const express = require('express');
const app = express();
const fs = require('fs')
const https = require('https')
const path = require('path')
var proxy = require('express-http-proxy')
const options = {
	
	key: fs.readFileSync(path.join(__dirname,'./keys/server.key')),
	cert: fs.readFileSync(path.join(__dirname,'./keys/server.crt'))
}

let server = https.createServer(options, app)
const wsInstance = require('express-ws')(app, server);

let clientss = {} // 0 set
// let clients = new Set()
let clientsWS = {}
let tousernamet = '';
let usernamet = '';
app.ws('/', ws => {
	ws.on('message', data => {
		try {
			const {
				username, 
				status,
				hourseNumber,
				type,
				sdp,
				tousername,
				iceCandidate
			} = JSON.parse(data)
			tousernamet = tousername
			usernamet = username
			// console.log(info.username)
			// !clients.has(username) && clients.add(username)
			!clientss[hourseNumber] && (clientss[hourseNumber] = new Set())
			!clientss[hourseNumber].has(username) && clientss[hourseNumber].add(username)
			
			// 没有存储当前的ws则存储一下
			// !clientsWS[username] && 
			clientsWS[username] = ws

			// 发送信息给告诉当前聊天室有哪些用户
			if(status === 0) {
				// 告诉当前加入聊天室的用户 当前的用户数量
				ws.send(JSON.stringify({
					status: 0,
					users: [...clientss[hourseNumber]],
					hourseNumber
				}))
			} else if(status === 1) { //发送来的为offer
				// 排除自己 将offer发送给所有人
				clientsWS[tousername].send(JSON.stringify({
					username,
					status,
					type,
					sdp,
					hourseNumber
				}))
				// wsInstance.getWss().clients.forEach(server => {
				// 	if (server !== ws) {
				// 		server.send(data);
				// 	} 
				// });
			} else if(status === 2) { //发来的为answer
				//根据username发送给对应的 发送offer的人
				clientsWS[tousername].send(JSON.stringify({
					status: 2,
					type,
					sdp,
					username,
					hourseNumber
				}))
			} else if(status === 3) {
				clientsWS[tousername].send(JSON.stringify({
					status: 3,
					iceCandidate,
					username,
					hourseNumber
				}))
			}

		} catch(e) {
			console.log(e.message)
			// console.log(typeof e)
			// console.log(e)
			// console.log(e.code)
			// if(tousernamet !== '') { // 清除掉不需要的东西 防止报错
			// 	// 删除掉当前用户信息
			// 	clients.has(tousernamet) && clients.delete(tousernamet)
			// 	// 删除掉当前用户ws实例
			// 	Object.keys(clientsWS).includes(tousernamet) && delete clientsWS[tousernamet]
			// 	// 告知其他客户端当前 username的用户退出
			// 	Object.values(clientsWS).forEach(ws => {
			// 		ws.send(JSON.stringify({
			// 			status: 4, //当前有用户退出
			// 			username: usernamet
			// 		}))
			// 	})
			// }
			// console.log(tousernamet)
			// console.log(e.message)
		}
	});

	ws.on('close',async (code, info) => {
		try {
			if(code === 3000) { // 3000代表关闭客户端
				const { username,hourseNumber } = JSON.parse(info)
				if(username && hourseNumber) { // 清除掉不需要的东西 防止报错
					// 删除掉当前用户信息
					clientss[hourseNumber].has(username) && clientss[hourseNumber].delete(username)
					// 告知其他客户端当前 username的用户退出
					Object.keys(clientsWS).forEach(async user => {
						user !== username &&  await clientsWS[user].send(JSON.stringify({
							status: 4, //当前有用户退出
							username,
							hourseNumber
						}))
					})
					// Object.values(clientsWS).forEach(async ws => {

					// 	await ws.send(JSON.stringify({
					// 		status: 4, //当前有用户退出
					// 		username,
					// 		hourseNumber
					// 	}))
					// })
					// 删除掉当前用户ws实例
					Object.keys(clientsWS).includes(username) && delete clientsWS[username]
				}
			}
		} catch(e) {
			console.log(e.message)
		}
	})

});

app.use(express.static(__dirname + '/dist'));
app.get('/index', (req, res) => {
	res.sendFile('./dist/index.html', { root: __dirname });
});

app.use('/',proxy('http://172.20.10.10:8081/'));

app.get('/p2p', (req, res) => {
	res.sendFile('./client/p2p.html', { root: __dirname });
});

server.listen(8888, () => {
	console.log('视频服务器启动成功!!!')
});